package com.timepies.activityutils;

import java.util.List;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

import com.timepies.R;
import com.timepies.adapter.PieAdapterExpandable;
import com.timepies.database.Service;
import com.timepies.domain.Intervallo;
import com.timepies.domain.Pie;

public class DettaglioExpandableList extends Activity implements
		OnChildClickListener {

	private Activity activity;
	private ExpandableListView list;
	private PieAdapterExpandable adapter;
	private Intervallo interval;
	private Thread thread = null;

	public DettaglioExpandableList(Activity activity, Intervallo interval) {

		this.activity = activity;
		this.interval = interval;
		this.list = (ExpandableListView) activity.findViewById(R.id.listView);
		this.list.setOnChildClickListener(this);
		reload();
		threadRefresh();
	}

	public void reload() {
		Log.d(this.toString(), "load");

		try {
			List<Pie> list = Service.getInstance(activity).getPiesGroups(
					activity);
			this.adapter = new PieAdapterExpandable(activity, interval, list);
			this.list.setAdapter(adapter);
		} catch (Exception e) {
			Log.e(this.toString(), "error : " + e.getMessage());
			Log.e(this.toString(), "error : " + e.getCause());
		}

	}

	private void threadRefresh() {

		thread = new Thread() {

			@Override
			public void run() {
				try {
					while (!isInterrupted()) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {

								TextView label = (TextView) activity
										.findViewById(R.id.label);
								TextView nomeEvento = (TextView) activity
										.findViewById(R.id.pie_testo);

								String txt = Intervallo.printTxtElapsed(
										interval.printStartDate(), true);

								txt += (interval.getIntervallo() > 0L) ? " da: "
										: " a: ";
								txt += nomeEvento.getText().toString();
								label.setText(txt);
								adapter.notifyDataSetChanged();
							}
						});
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
				}
			}
		};

		thread.start();

	}

	public void threadStop() {
		if (thread != null)
			thread.interrupt();

	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		int itemType = ExpandableListView.getPackedPositionType(id);
		if (itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			Log.e(this.toString(), "TYPE_GROUP");
		}
		if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			Log.e(this.toString(), "TYPE_CHILD");
		}

		return false;
	}

}
